<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import type { IOrder } from '@/types/order'
import { getOrderDetailAPI } from '@/services/payment'
import { aginDetailAPI, cancelOrderAPI, pageOrderStatusAPI } from '@/services/order'
import { useCategory, useOrder, useReview, useMemberStore } from '@/stores'
import { formatChineseJson, formateStr } from '@/utils/http'
import type { IcartItem } from '@/types/cart'
const { addOrderData } = useOrder()
const { setReviewData } = useReview()
const { getBuyMethodName, setBuyMethodActiveIndex } = useCategory()
const { getUserInfo } = useMemberStore()
const { safeAreaInsets } = uni.getSystemInfoSync()

const orderInfo = ref({} as IOrder)
const query = defineProps<{
  orderId: string
}>()

const detailOrderRequest = async () => {
  const res = await getOrderDetailAPI({
    orderId: query.orderId,
  })
  orderInfo.value = res.data

  startCountdown(orderInfo.value.createDate)
}

onLoad(() => {
  detailOrderRequest()
})

const payHandler = (item: IOrder) => {
  if (item.orderStatus === 0) {
    uni.navigateTo({
      url: '/pagesOrder/payment/payment?orderId=' + item.id,
    })
  }
}

const cancel = async (reason: string) => {
  if (orderInfo.value.orderStatus === 0) {
    await cancelOrderAPI({
      orderId: orderInfo.value.id as number,
      userId: getUserInfo()?.id,
      reason,
    })
    orderInfo.value.orderStatus = 6
    clearInterval(timer.value)
  }
}

const orderCancelHandler = async (reason: string) => {
  uni.showModal({
    content: '确定取消订单？',
    success: async (res: any) => {
      if (res.confirm) {
        cancel(reason)
      }
    },
  })
}

const createOrderHandler = async (item: IOrder) => {
  const res = await aginDetailAPI({
    orderId: item.id,
  })
  setBuyMethodActiveIndex(item.eatType)
  addOrderData(res.data as IcartItem[])
  uni.navigateTo({ url: '/pagesOrder/create/create' })
}

const navViewHandler = (info: IOrder) => {
  setReviewData(info.orderItemsList)
  uni.navigateTo({ url: '/pagesOrder/review/review?orderId=' + query.orderId })
}

const expireTime = ref(0) // 过期时间戳
const timer = ref(null as any)
const minute = ref('30')
const second = ref('00')

// 格式化：补零
const pad = (num: number) => String(num).padStart(2, '0')

// 启动倒计时
const startCountdown = (createTime: string) => {
  // 1. 将 "2025-09-05 13:22:45" 转为 Date 对象，再转为毫秒时间戳
  const createTimeMs = new Date(createTime).getTime()

  // 2. 计算过期时间：创建时间 + 30分钟（毫秒）
  expireTime.value = createTimeMs + 30 * 60 * 1000

  // 3. 开始倒计时逻辑
  const update = () => {
    const now = Date.now()
    const remainSeconds = Math.floor((expireTime.value - now) / 1000)

    if (remainSeconds <= 0) {
      minute.value = '00'
      second.value = '00'
      cancel('订单超时，自动取消订单')
    } else {
      minute.value = pad(Math.floor(remainSeconds / 60))
      second.value = pad(remainSeconds % 60)
    }
  }

  update() // 立即执行一次
  timer.value = setInterval(update, 1000)
}

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>
<template>
  <view class="detail-order-page">
    <scroll-view class="detail-order-scroll" scroll-y>
      <view class="main">
        <!-- 倒计时显示 -->
        <view v-if="orderInfo.orderStatus === 0" class="countdown-timer">
          请尽快支付，
          <text class="minute">{{ minute }}</text>
          <text class="colon">分</text>
          <text class="second">{{ second }}</text>
          <text class="colon">秒</text>
          后，将自动取消订单
        </view>
        <view v-if="orderInfo.orderStatus === 6" class="cancel-status">
          <text class="txt">订单已取消</text>
        </view>
        <view class="card" v-if="orderInfo.orderStatus === 2">
          <view class="content">
            <text class="title">配送中</text>
            <text class="time"> 预计 14:30 送达</text>
          </view>

          <image class="avatar" mode="aspectFill" :src="getUserInfo().avatarUrl"></image>
        </view>

        <view class="order-info">
          <view class="info-item">
            <text class="label">订单编号</text>
            <text class="value">{{ orderInfo.tradeNo }}</text>
          </view>
          <view class="info-item">
            <text class="label">下单时间</text>
            <text class="value">{{ orderInfo.createDate }}</text>
          </view>
          <view class="info-item">
            <text class="label">支付方式</text>
            <text class="value">{{
              orderInfo.paymentMethod === 0 ? '微信支付' : '支付宝支付'
            }}</text>
          </view>
          <view class="info-item">
            <text class="label">备注</text>
            <text class="value">{{ orderInfo.remark }}</text>
          </view>
        </view>

        <view class="order-content-list">
          <view class="header"><text>商品清单</text></view>
          <navigator
            :url="`/pages/goods/goods?id=${2}`"
            hover-class="none"
            class="order-content-item"
            v-for="item in orderInfo.orderItemsList"
            :key="item.id"
          >
            <image class="left" :src="item.image" mode="scaleToFill" />
            <view class="center">
              <view class="name">{{ item.goodsName }}</view>
              <view class="spec">
                <rich-text :nodes="formateStr(item)"></rich-text>
              </view>
            </view>
            <view class="right">
              <text class="price">¥{{ item.price }}</text>
              <text class="num">x{{ item.quantity }}</text>
            </view>
          </navigator>
        </view>
        <view class="delivery-info" v-if="orderInfo.eatType === 2">
          <view class="header"><text>配送信息</text></view>
          <view class="address">
            <view class="icon"><text class="iconfont icon-address"></text></view>
            <view class="meta">
              <text class="title">{{ orderInfo.deliveryAddress }}</text>
              <text class="con">{{ orderInfo.deliveryName }} {{ orderInfo.deliveryPhone }}</text>
            </view>
          </view>
          <view class="delivery-time">
            <view class="icon"><text class="iconfont icon-RectangleCopy13"></text></view>
            <text class="text">期望送达时间：{{ orderInfo.deliveryTime }}</text>
          </view>
        </view>
        <view class="delivery-info" v-else>
          <view class="address">
            <view class="icon"><text class="iconfont icon-address"></text></view>
            <view class="meta">
              <text class="title">就餐方式</text>
              <text class="con">{{ getBuyMethodName(orderInfo.eatType) }}</text>
            </view>
          </view>
        </view>

        <view class="order-summary">
          <view class="header">
            <text>支付详情</text>
          </view>
          <view class="summary-item">
            <text class="label">商品总价</text>
            <text class="value">¥{{ orderInfo.totalAmount }}</text>
          </view>
          <view class="summary-item">
            <text class="label">配送费</text>
            <text class="value">¥{{ orderInfo.discountAmount }}</text>
          </view>
          <view class="summary-item discount">
            <text class="label">优惠</text>
            <text class="value">-¥{{ orderInfo.discountAmount }}</text>
          </view>
          <view class="summary-item total">
            <text class="label">实付金额</text>
            <text class="value">¥{{ orderInfo.finalAmount }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="operate-btn" v-if="orderInfo.orderStatus === 0">
      <button class="btn btn-service" @tap="payHandler(orderInfo)">立即支付</button>
      <button class="btn btn-cancel" @click="orderCancelHandler('用户手动取消订单')">
        取消订单
      </button>
    </view>
    <view class="operate-btn" v-if="orderInfo.orderStatus === 3">
      <button class="btn btn-service" @tap="createOrderHandler(orderInfo)">再次购买</button>
      <button class="btn btn-cancel" @click="navViewHandler(orderInfo)">去评价</button>
    </view>

    <!-- <view class="order-operation" v-else-if="item.orderStatus === 3">
              <view class="btn cancel" @click="createOrderHandler(item)">再次购买</view>
              <navigator class="btn pay" url="/pagesOrder/review/review" hover-class="none">
                去评价
              </navigator>
            </view> -->
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

.order-countdown {
  padding: 30rpx;
  background-color: #fff9f0;
  color: #e67e22;
  font-size: 28rpx;
  text-align: center;
  border-radius: 16rpx;
  margin: 40rpx;
  box-shadow: 0 6rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-countdown .txt {
  font-weight: bold;
  color: #d35400;
}

.countdown-timer {
  margin-top: 20rpx;

  justify-content: center;
  text-align: center;

  display: flex;
  align-items: center;
  background-color: #fff9f0;
  color: #e67e22;
  font-size: 28rpx;
  line-height: 1.5;
  padding: 20rpx 30rpx;
  border-radius: 20rpx;
  margin: 20rpx 0;
  text-align: center;
  box-shadow: 0 6rpx 10rpx rgba(0, 0, 0, 0.05);

  .minute,
  .second {
    font-weight: bold;
    display: inline-block;
    background-color: #d35400;
    color: white;
    border-radius: 4rpx;
    font-size: 28rpx;
    padding: 0 8rpx;
    margin: 0 10rpx;
  }

  .colon {
    color: #e67e22;
  }
}
.expired-tip {
  margin-top: 20rpx;
  color: #e74c3c;
  font-weight: bold;
}
page {
  height: 100%;
  overflow: hidden;
  background-color: $background-color;
}
.detail-order-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: $background-color;
  .detail-order-scroll {
    flex: 1;
  }
  .main {
    flex: 1;
    padding: 0 32rpx 32rpx;
    background-color: $background-color;

    .card {
      padding: 32rpx;
      border-radius: $border-medium-radius;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
      background: linear-gradient(to bottom, #d5f5e3, #a6efaa);
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 32rpx;

      .content {
        display: flex;
        flex-direction: column;
        justify-content: center;
        .title {
          font-size: 48rpx;
          color: #2e7d32;
          margin-bottom: 10rpx;
        }
        .time {
          font-size: 32rpx;
          color: #666666;
          display: flex;
          align-items: center;
          &::before {
            content: '\e6eb';
            font-family: 'iconfont' !important;
            color: #666666;
            font-size: 40rpx;
            margin-right: 10rpx;
          }
        }
      }
      .avatar {
        width: 128rpx;
        height: 128rpx;
        border-radius: 50%;
      }
    }

    .order-info {
      display: flex;
      flex-direction: column;
      padding: 32rpx;
      background-color: #fff;
      border-radius: $border-medium-radius;
      margin-bottom: 32rpx;

      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32rpx;

        &:nth-child(4) {
          margin-bottom: 0;
        }

        .label {
          font-size: $font-medium-size;
          color: $font-color;
          font-weight: $font-weight;
        }

        .value {
          font-size: $font-medium-size;
          color: $font-color;
          font-weight: $font-weight;
        }
      }
    }

    .order-content-list {
      margin-bottom: 32rpx;
      border-radius: $border-medium-radius;
      background-color: #fff;
      padding: 32rpx;
      .header {
        padding-bottom: 16rpx;
        text {
          color: #000;
          font-size: $font-medium-size;
          font-weight: $font-medium-weight;
        }
      }
      .order-content-item {
        display: flex;
        align-items: center;
        padding: 16rpx 0;
        position: relative;
        &::after {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          content: '';
          border: 1px solid $border-color;
        }

        &:last-child {
          padding-bottom: 0;
          &::after {
            display: none;
          }
        }

        .left {
          width: 160rpx;
          height: 160rpx;
          border-radius: $border-small-radius;
          overflow: hidden;

          image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .center {
          flex: 1;
          margin-left: 32rpx;
          display: flex;
          flex-direction: column;

          .name {
            font-size: $font-medium-size;
            color: $good-font-title-color;
            font-weight: $font-medium-weight;
            margin-bottom: 10rpx;
          }

          .spec {
            font-size: $font-size;
            color: $good-font-con-color;
            font-weight: $font-regular-weight;
          }
        }

        .right {
          text-align: right;
          display: flex;
          flex-direction: column;

          .price {
            font-size: $font-medium-size;
            color: $color;
            font-weight: $font-medium-weight;
            margin-bottom: 10rpx;
          }

          .num {
            font-size: $font-size;
            color: $good-font-con-color;
            font-weight: $font-regular-weight;
          }
        }
      }
    }

    .delivery-info {
      margin-bottom: 32rpx;
      border-radius: $border-medium-radius;
      background-color: #fff;
      padding: 32rpx;
      .header {
        padding-bottom: 32rpx;
        text {
          color: #000;
          font-size: $font-medium-size;
          font-weight: $font-medium-weight;
        }
      }

      .address {
        display: flex;
        align-items: center;
        padding-bottom: 32rpx;

        .icon-jinru {
          color: #9ca3af;
        }

        .icon {
          margin-bottom: auto;
          padding-right: 30rpx;
          .iconfont {
            font-size: 40rpx;
            color: $color;
          }
          &.edit {
            padding-right: 0;
            margin-left: 10rpx;
            .iconfont {
              font-size: 30rpx;
              margin-bottom: auto;
              color: $icon-color;
            }
          }
        }

        .meta {
          flex: 1;
          display: flex;
          flex-direction: column;

          .title {
            font-size: $font-medium-size;
            font-weight: $font-medium-weight;
            color: $good-font-title-color;
            margin-bottom: 10rpx;
          }

          .con {
            font-size: $font-size;
            color: $font-color;
          }
        }
      }

      .delivery-time {
        display: flex;
        align-items: center;
        .icon {
          margin-bottom: auto;
          padding-right: 30rpx;
          .iconfont {
            font-size: 40rpx;
            color: $color;
          }
        }

        .text {
          font-size: $font-medium-size;
          font-weight: 500;
          color: #111827;
        }
      }
    }

    .order-summary {
      display: flex;
      flex-direction: column;
      padding: 32rpx;
      background-color: #fff;
      border-radius: $border-medium-radius;
      margin-bottom: 32rpx;

      .header {
        padding-bottom: 32rpx;
        text {
          color: #000;
          font-size: $font-medium-size;
          font-weight: $font-medium-weight;
        }
      }

      .summary-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32rpx;

        .label {
          font-size: $font-medium-size;
          color: #666666;
          font-weight: $font-weight;
        }

        .value {
          font-size: $font-medium-size;
          color: $font-color;
          font-weight: $font-weight;
        }

        &.discount {
          .value {
            color: $color;
          }
        }

        &.total {
          color: #000;
          padding: 32rpx 0;
          margin-bottom: 0;

          position: relative;
          &::before {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            content: '';
            border: 1px solid $border-color;
          }
          .value {
            color: $price-total-font-color;
          }
        }
      }
    }
  }

  .cancel-status {
    .txt {
      height: 56rpx;
      border-radius: 28rpx;
      text-align: center;
      background-color: #fff;
      box-sizing: border-box;
      font-size: 28rpx;
      color: $color;
      font-weight: $font-weight;
      padding: 4px 22rpx;
      border: 1px solid #4b5563;
      color: #4b5563;
      background-color: #f3f4f6;
    }
    margin: 30rpx 0;
  }
  .operate-btn {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    gap: 32rpx;
    padding: 32rpx;
    background-color: #fff;
    .btn {
      flex: 1;
      height: 100rpx;
      line-height: 100rpx;
      border-radius: 50rpx;
      text-align: center;
      background-color: #fff;
      box-sizing: border-box;
      &.btn-service {
        font-size: 32rpx;
        color: $color;
        font-weight: $font-weight;
        border: 1px solid $color;
      }
      &.btn-cancel {
        font-size: 32rpx;
        color: #ff5252;
        font-weight: $font-weight;
        border: 1px solid #ff5252;
        height: 100rpx;
      }
    }
  }
}
</style>
